<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-row>
        <el-col :span="8">
          <el-select class="filter-item" v-model="queryParams.groupId" placeholder="全部门站" @change="selectGroupChange">
            <el-option v-for="item in  groups" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="16">
          <!--<el-button-group>-->
          <!--<el-tooltip class="item btn-ww" effect="dark" content="编辑设置" placement="top">-->
            <!--<el-button class="item btn-ww pull-right"  :disabled="!queryParams.groupId" @click="dialogFormVisible=true"><i class="el-icon-edit el-col-pull-2">编辑设置</i></el-button>-->
          <!--</el-tooltip>-->
          <!--<el-tooltip class="item btn-ww" effect="dark" content="设备注册" placement="top">-->
            <el-button  class="item btn-ww pull-right" style="margin-left: 5px" :disabled="!queryParams.groupId" @click="dialogRegisterVisible=true"><i
              class="el-icon-circle-plus-outline">设备注册</i></el-button>
          <!--</el-tooltip>-->
          <!--</el-button-group>-->
        </el-col>
      </el-row>
    </div>


    <el-table class="table-border color-none" border :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="正在努力加载中。。。" style="width: 100%"
              @expand-change="rowExpand">
      <el-table-column label="NO." type="index" >

      </el-table-column>
      <el-table-column label="设备Id" prop="sn" align="center">
      </el-table-column>
      <!--<el-table-column label="版本号" prop="version"  align="center">-->
      <!--</el-table-column>-->
      <el-table-column label="电量" prop="batteryLevel"  align="center">
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @current-change="handleCurrentChange"
                     :current-page.sync="queryParams.pageNumber"
                     :page-size="queryParams.pageSize"
                     layout="prev, pager, next"
                     :total="total">
      </el-pagination>
    </div>


    <!-- 设备注册 -->
    <el-dialog title="设备注册" :visible.sync="dialogRegisterVisible">
      <el-form :rules="rules" :model="rgParam" ref="registerForm" label-position="left" label-width="100px"
               style='width: 400px; margin-left:50px;'>
        <el-form-item label="请输入sn号" prop="sn">
          <el-input placeholder="请输入sn号" v-model="rgParam.sn" clearable></el-input>
        </el-form-item>
        <el-form-item label="请选择分组" prop="groupId">
          <el-select class="filter-item" v-model="rgParam.groupId" placeholder="请选择" @change="selectGroupChange">
            <el-option v-for="item in  groups" :key="item.id +''" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="el-col-lg-offset-3" @click="cancelRg">取 消</el-button>
        <el-button type="primary" @click="registerDevices">注 册</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { fetchList } from '../../../api/group'
  import { fetchDeviceList, registerDevice } from '../../../api/device'
  import { headerData, deviceKeyEnVal, units, zeroVals } from './HeaderData'

  export default {
    name: 'complexTable',
    directives: {},
    data() {
      return {
        time: null,
        rgLoading: null,
        groups: [],
        headerData,
        deviceKeyEnVal,
        selectRowData: {},
        tableData: [],
        formThead: headerData,
        dialogFormVisible: false,
        dialogRegisterVisible: false,
        tableKey: 0,
        list: null,
        queryParams: {
          groupId: '',
          pageNumber: 1,
          pageSize: 10
        },
        total: 0,
        listLoading: true,
        temp: {
          id: '',
          name: ''
        },
        rgParam: {
          sn: '',
          groupId: ''
        },
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          sn: [{ required: true, message: 'sn必填', trigger: 'blur' }],
          groupId: [{ required: true, message: 'sn必填', trigger: 'blur' }]
        }
      }
    },
    filters: {},
    created() {
      this.resetSelectItems()
      this.getGroups()
    },
    methods: {
      zeroVals,
      headerClass(obj) {
        const headername = obj.column.label
        if (headername === 'DefaultTemperature' || headername === 'DefaultPressure') {
          return 'hide'
        }
        return ''
      },
      headerRender(h, { column, $index }) {
        let unit = ''
        if (units[column.label]) {
          unit = '(' + units[column.label] + ')'
        }
        const label = column.label + unit
        return h('el-tooltip', {
          props: {
            content: deviceKeyEnVal[column.label] || 'sb',
            placement: 'top'
          }
        },
        [h('span', {
          style: {
            margin: '0 5px',
            display: 'inline-block',
            width: '100%'
          }
        }, label)])
      },
      pushHistory(sn) {
        if (!sn) {
          this.$message.error('sn不能为空')
          return
        }
        this.$router.push({ path: '/device/history', query: { sn: sn.replace(/\0/g, '') }})
      },
      selectItmesChange() {
        localStorage.setItem('current-items', JSON.stringify(this.formThead))
        this.dialogFormVisible = false
      },
      resetSelectItems() {
        const obj = JSON.parse(localStorage.getItem('current-items')) || this.headerData
        if (obj) {
          this.formThead = []
          obj.forEach((val) => {
            if (val.index >= 0) {
              this.formThead.push(this.headerData[val.index])
            }
          })
        }
      },
      cancelRg() {
        this.dialogRegisterVisible = false
        if (this.rgLoading) {
          this.rgLoading.close()
        }
        if (this.time) {
          clearInterval(this.time)
        }
      },
      selectGroupChange(groupId) {
        this.queryParams.groupId = groupId
        this.queryParams.pageNumber = 1
        this.getDevices()
      },
      rowExpand(row) {
        this.selectRowData = row
      },
      getDevices() {
        fetchDeviceList(this.queryParams).then(data => {
          this.list = data.data.content
          this.total = data.data.totalElements
        })
      },
      getGroups() {
        this.listLoading = true
        fetchList().then(data => {
          if (data.data.length === 0) {
            this.$message.error('请先新建门站！')
          }
          this.groups = data.data
          this.rgParam.groudId = this.groups[0] ? this.groups[0].id : ''
          this.queryParams.groupId = this.groups[0] ? this.groups[0].id : ''
          this.getDevices()
          this.listLoading = false
        })
      },
      registerDevices() {
        if (!this.rgParam.sn || this.rgParam.sn.length < 1) {
          this.$message({
            message: 'SN号不能为空',
            type: 'error'
          })
          return
        }
        this.rgLoading = this.$loading({
          lock: true,
          text: '设备注册中请耐心等待。',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.time = setInterval(this.rg(), 1000)
      },
      rg() {
        const that = this
        registerDevice(this.rgParam.sn, this.rgParam.groupId).then(data => {
          if (data.data.success) {
            that.rgLoading.close()
            clearInterval(that.time)
            that.$message({
              message: '注册成功',
              type: 'success'
            })
            that.dialogRegisterVisible = false
            that.getDevices()
          }else{
            that.$message({
              message: data.msg,
              type: 'error'
            })
            this.cancelRg()
          }
        }).catch(error => {
          console.log(error)
          that.rgLoading.close()
          clearInterval(that.time)
        })
      },
      handleCurrentChange(val) {
        this.queryParams.pageNumber = val
        this.getDevices()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      resetTemp() {
        this.temp = {
          name: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // createGroup(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            // })
          }
        })
      },
      goto(row) {
        this.$router.push({path: '/device/device_info'})
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            // updateGroup(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            // })
          }
        })
      },
      handleDelete(row) {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      }
    }
  }
</script>
<style lang="css" scoped>
  .el-checkbox:first-child {
    margin-left: 30px;
  }
  .el-select > .el-input{
    background-image: none !important;
  }
  .is-error > .el-input{
    border: 1px red solid;
  }
</style>
